package com.j2eefast.flowable.bpm.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j2eefast.common.core.utils.ResponseData;
import com.j2eefast.flowable.bpm.entity.BpmBidQualitySafetyEntity;
import com.j2eefast.flowable.bpm.entity.BpmBidQualitySafetyEntity;
import com.j2eefast.flowable.bpm.entity.BpmFormDraftEntity;
import com.j2eefast.flowable.bpm.entity.StartProcessInstanceEntity;
import com.j2eefast.flowable.bpm.mapper.BpmBidqualitySafetyMapper;
import com.j2eefast.framework.utils.UserUtils;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 项目质量安全监管表ervice接口
 * @author: SUMMER
 * @date 2021-06-4 22:19
 */
@Service
public class BpmBidQualitySafetyService extends ServiceImpl<BpmBidqualitySafetyMapper, BpmBidQualitySafetyEntity> {

	@Resource
	@Lazy
	private BpmBidQualitySafetyService bpmBidQualitySafetyCeService;

	@Autowired
	private FlowableProcessInstanceService flowableProcessInstanceService;
	@Autowired
	private BpmFormDraftService bpmFormDraftService;

	/**
	 * 保存表单并发起审批
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData addForm(BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		bpmBidQualitySafetyEntity.setId(IdUtil.fastSimpleUUID());
		bpmBidQualitySafetyEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		bpmBidQualitySafetyEntity.setTitle(this.formatTitle(bpmBidQualitySafetyEntity.getTitle(), bpmBidQualitySafetyEntity));
		ResponseData returnStart = this.startProcess(bpmBidQualitySafetyEntity);
		if(!returnStart.get("code").equals("00000")) {
			return returnStart;
		}
		String processInstanceId = ((ProcessInstance)returnStart.get("data")).getProcessInstanceId();

		bpmBidQualitySafetyEntity.setProcessInstanceId(processInstanceId);
		BpmFormDraftEntity bpmFormDraftEntity = this.prepareFormDraft(bpmBidQualitySafetyEntity,false);
		bpmFormDraftService.save(bpmFormDraftEntity);
		return bpmBidQualitySafetyCeService.save(bpmBidQualitySafetyEntity)? ResponseData.success(): ResponseData.error("数据插入失败!");
	}

	/**
	 * 根居ID获取对象
	 */
	public BpmBidQualitySafetyEntity getFormById(String id){
		return this.getById(id);
	}

	protected String formatTitle(String title, BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity){
		//项目报备申请-{创建人}（{创建时间}）
		title = title.replace("{创建人}", bpmBidQualitySafetyEntity.getCreateBy());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(bpmBidQualitySafetyEntity.getCreateTime());
		return title.replace("{创建时间}", dateString);
	}

	/**
	 * 启动流程实例
	 * @param bpmBidQualitySafetyEntity
	 * @return
	 */
	private ResponseData startProcess(BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		StartProcessInstanceEntity startProcessInstanceVo = new StartProcessInstanceEntity();
		startProcessInstanceVo.setBusinessKey(bpmBidQualitySafetyEntity.getId());
		startProcessInstanceVo.setCreator(String.valueOf(UserUtils.getUserId()));
		startProcessInstanceVo.setCurrentUserCode(String.valueOf(UserUtils.getUserId()));
		startProcessInstanceVo.setFormName(bpmBidQualitySafetyEntity.getTitle());
		startProcessInstanceVo.setSystemSn("system");
		//startProcessInstanceVo.setProcessDefinitionKey(bpmBidOpeningEntity.getModelKey());
		startProcessInstanceVo.setProcessDefinitionKey(bpmBidQualitySafetyEntity.getModelKey());
		Map<String, Object> variables = new HashMap<>();
		variables.put("priority", bpmBidQualitySafetyEntity.getPriority());
		startProcessInstanceVo.setVariables(variables);
		return flowableProcessInstanceService.startProcessInstanceByKey(startProcessInstanceVo);
	}


	public BpmFormDraftEntity prepareFormDraft(BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity, boolean active){
		//写入草稿
		BpmFormDraftEntity bpmFormDraftEntity = new BpmFormDraftEntity();
		bpmFormDraftEntity.setTitle(bpmBidQualitySafetyEntity.getTitle());
		bpmFormDraftEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		//这是一个固定的数据，每个表单表有一个url prefix
		bpmFormDraftEntity.setUrl("bpm/bidqualitysafety");
		bpmFormDraftEntity.setStatus("1");
		bpmFormDraftEntity.setPriority(bpmBidQualitySafetyEntity.getPriority());
		bpmFormDraftEntity.setFormDataId(bpmBidQualitySafetyEntity.getId());
		bpmFormDraftEntity.setCreateTime(new Date());
		if(bpmBidQualitySafetyEntity.getProcessInstanceId()!=null){
			bpmFormDraftEntity.setProcessInstanceId(bpmBidQualitySafetyEntity.getProcessInstanceId());
		}
		String activeFlag = active?"1":"0";
		bpmFormDraftEntity.setActive(activeFlag);
		return bpmFormDraftEntity;
	}


	/**
	 * 将表单进行保存，不发起流程
	 * @param bpmBidQualitySafetyEntity
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData saveAsDraft(BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		bpmBidQualitySafetyEntity.setId(IdUtil.fastSimpleUUID());
		bpmBidQualitySafetyEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		bpmBidQualitySafetyEntity.setTitle(this.formatTitle(bpmBidQualitySafetyEntity.getTitle(), bpmBidQualitySafetyEntity));
		bpmBidQualitySafetyEntity.setStatus("0");
		//写入草稿数据
		BpmFormDraftEntity bpmFormDraftEntity = this.prepareFormDraft(bpmBidQualitySafetyEntity,true);
		bpmFormDraftService.save(bpmFormDraftEntity);
		return bpmBidQualitySafetyCeService.save(bpmBidQualitySafetyEntity)? ResponseData.success(): ResponseData.error("数据插入失败!");
	}

	/**
	 * 将待发表单重新发起流程
	 * @param formDraftId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData sendForm(String formDraftId){
		//更新FormDraft的状态
		BpmFormDraftEntity bpmFormDraftEntity = bpmFormDraftService.getById(formDraftId);
		BpmFormDraftEntity toUpdateDraft = new BpmFormDraftEntity();
		toUpdateDraft.setStatus("2");
		toUpdateDraft.setId(bpmFormDraftEntity.getId());
		bpmFormDraftService.updateDataById(toUpdateDraft);
		BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity = bpmBidQualitySafetyCeService.getFormById(bpmFormDraftEntity.getFormDataId());
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		ResponseData returnStart = this.startProcess(bpmBidQualitySafetyEntity);
		if(!returnStart.get("code").equals("00000")){
			return returnStart;
		}
		BpmBidQualitySafetyEntity toUpdate = new BpmBidQualitySafetyEntity();
		toUpdate.setId(bpmBidQualitySafetyEntity.getId());
		toUpdate.setProcessInstanceId(((ProcessInstance)returnStart.get("data")).getProcessInstanceId());
		return bpmBidQualitySafetyCeService.updateById(toUpdate)? ResponseData.success(): ResponseData.error("发起流程失败!");
	}
	/**
	 * 修改未发起审批的表单
	 * @param
	 * @return
	 */
	public boolean editForm(BpmBidQualitySafetyEntity bpmBidQualitySafetyEntity){
		BpmFormDraftEntity bpmFormDraftEntity = bpmBidQualitySafetyCeService.prepareFormDraft(bpmBidQualitySafetyEntity, true);
		bpmFormDraftService.updateByFormDataId(bpmFormDraftEntity);
		return this.updateById(bpmBidQualitySafetyEntity);
	}
	}